package com.heima.search.service.Impl;

import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索记录
     *
     * @param keywords 搜索关键词
     * @param userId   用户Id
     */
    @Async
    @Override
    public void insert(String keywords, Long userId) {
        //检验参数
        if(keywords==null||userId==null){
            return;
        }
        //查询当前用户的搜索关键词
        Query query = Query.query(Criteria.where("keyword").is(keywords).and("userId").is(userId));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        if(apUserSearch==null){
            //不存在，则需先判断总记录数是否达到10个，达到则删除最早创建的记录，没有达到10个则直接创建
            Query query1 = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC, "createdTime"));
            List<ApUserSearch> apUserSearches = mongoTemplate.find(query1, ApUserSearch.class);
            if(apUserSearches.size()==10){
                //总记录数达到10个，删除最早创建的搜索记录
                ApUserSearch lastUserSearch=apUserSearches.get(apUserSearches.size()-1);
                mongoTemplate.remove(Query.query(Criteria.where("id").is(lastUserSearch.getId())), ApUserSearch.class);
            }
            //创建
            apUserSearch = new ApUserSearch();
            apUserSearch.setUserId(userId);
            apUserSearch.setKeyword(keywords);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.insert(apUserSearch);
        }else{
            //存在，则只需要修改创建时间
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }
    }

    @Override
    public ResponseResult historyLoad() {
        //从mongodb库中获取search表中的该用户的所有搜索记录
        Query query = Query.query(Criteria.where("userId").is(AppThreadLocalUtil.getUser().getId())).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        if(apUserSearches!=null){
            return ResponseResult.okResult(apUserSearches);
        }else{
            return ResponseResult.okResult(null);
        }
    }

    @Override
    public ResponseResult historyDel(ApUserSearch apUserSearch) {
        //从mongodb库中删除指定搜索记录
        Query query = Query.query(Criteria.where("userId").is(AppThreadLocalUtil.getUser().getId()).and("id").is(apUserSearch.getId()));
        mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
